#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "defs.h"
#include "help.h"

void help(int index)
{
   int i=0, j, ch, place=0;
   char string[60], topic[20];
   static char screen[2000], *helpbuf, *tempptr;
   FILE *ifp;
   struct text_info ti;

   if((ifp=fopen("help.hlp","r"))==NULL) return;
   sprintf(topic,"HelpTopic%d",index);
   while(1)
     {if(fscanf(ifp,"%s",string)==EOF) {fclose(ifp); return;}
      if(strcmp(string,topic)==0) break;
     }
   if((helpbuf=(char *) malloc(1))==NULL) {fclose(ifp); return;}
   while(1)
     {ch=getc(ifp);
      if(ch=='|' || ch==EOF) {helpbuf[i++]=0; break;}
      helpbuf[i++]=ch;
      if((tempptr=(char *) realloc(helpbuf,i+1))!=NULL) helpbuf=tempptr;
     }
   fclose(ifp);

   gettextinfo(&ti);
   gettext(11,6,70,20,screen);
   window(11,6,70,20); textbackground(BLUE); textcolor(WHITE); clrscr();
   gotoxy(2,1); cprintf("CNCPro                            Al's build Sep 9, 2007");
   box(11,7,70,20, BLUE,BLACK,WHITE,WHITE);
   gotoxy(13,1); cprintf("    PgUp PgDn Esc");
   gotoxy(13,1); putch(24); gotoxy(15,1); putch(25);

   window(13,9,68,18);

   while(1)
     {clrscr();
      i=place;
      for(j=0;j<10;j++)
        {if(helpbuf[i]=='\n') {gotoxy(1,j+1); i++;}
         while(helpbuf[i]!=0)
           {if(helpbuf[i]=='\n') break;
            putch(helpbuf[i++]);
           }
         if(helpbuf[i]==0) break;
        }
      ch=getch();
      if (ch == 27) break;
      if (ch > 0) continue;
      ch = getch();
      switch (ch)
        {case 72 : //up arrow
            if(place>0) place--;
            while(helpbuf[place]!='\n' && place>0) place--;
            break;
         case 80 : //down arrow
            if(helpbuf[i]!=0) place++;
            while(helpbuf[place]!='\n' && helpbuf[i]!=0) place++;
            break;
         case 73 : //page up
            for(j=0;j<10;j++) {if(place>0) place--; while(helpbuf[place]!='\n' && place>0) place--;}
            break;
         case 81 : //page down
            if(helpbuf[i]!=0) place=i;
            break;
       }
     }
   free(helpbuf);
   puttext(11,6,70,20,screen); 
   textattr(ti.attribute);
   window(ti.winleft, ti.wintop, ti.winright, ti.winbottom);
}
